package util;

import static core.SeleneseTestCaseEx.u;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Properties;
import java.util.regex.*;
import java.util.TimeZone;
import jxl.*;
import jxl.write.WritableWorkbook;
import core.SeleneseTestCaseEx;


public class Util {
	private TestConfiguration tc = TestConfiguration.getInstance();
	private FileWork fw = FileWork.getInstance();
	private String testEmail = "";
	private String artistName = "";
	private String albumName = "";
	private String trackName = "";
	private String videoName = "";
	private String ringtoneName = "";
	private String goodName = "";
	private String groupName = "";
	private String messageName = "";
	
	
	public String empVl(String inpString) {
		if (inpString.contentEquals("")) {
			return "[EMPTY]";
		} else {
			return inpString;
		}
	}
	
	public String getTimeNow() {
		Date now = new Date();
		return dataTime2String(now, "HH:mm:ss");
	}
	
	public String getDateNow() {
		Date now = new Date();
		return dataTime2String(now, "dd-MMM-yyyy");
	}
	
	public String getDateTimeNow() {
		Date now = new Date();
		return dataTime2String(now, "dd-MMM-yyyy, HH:mm:ss");
	}
	
	public String getTime(Date time) {
		return dataTime2String(time, "HH:mm:ss");
	}
	
	public String getTimeZone() {
		TimeZone tz = TimeZone.getDefault();
		Integer i = 0;
		
		i = tz.getRawOffset() / 1000 / 60 / 60; //convert msec to hours
		return ((i >=0) ? ("GMT+" + i + ".00") : ("GMT-" + i + ".00"));
	}	
	
	public String dataTime2String(Date date, String mask) {
		 SimpleDateFormat format = new SimpleDateFormat(mask);
		 return format.format(date);
	}

    /**Encodes specified string into HTML format by replacing special characters (&amp;, &gt;, &lt;, &quot;, SPACE, LINE BREAK, "\n")
     * with appropriate &amp;; codes. If string contains html-formatting then no encoding will be done.
     * @param strToEncode Specifies the string for encoding.
     * @return Encoded into HTML format string
     */
    public String encodeHTML(String strToEncode) {
    	Pattern ptrn = null;
        String[] patternsArr = {"b", "p", "font", "i", "table", "h1", "h2", "h3", "h4",  "Div"};
        
        boolean res;
        res = false;
        
        int k;
        String expression;
        String tagPattern;
        
        String result = "";
        for(k = 0; k < 10; k++) {
            tagPattern = patternsArr[k];
            expression = "<\\s*" + tagPattern + ".*\\n*>.*\\n*<\\s*/" + tagPattern + "\\s*>";
            ptrn = Pattern.compile(expression);
            res = ptrn.matcher(strToEncode).matches();

            if (res) {
            	result = strToEncode;
            } else {
            	//strToEncode = strToEncode.replace("&", "&amp;");
            	strToEncode = strToEncode.replace(">", "&gt;");
            	strToEncode = strToEncode.replace("<", "&lt;");
            	strToEncode = strToEncode.replace("\"\"", "&quot;");
            	strToEncode = strToEncode.replace("  ", "&nbsp;&nbsp;");
            	strToEncode = strToEncode.replace("\\n", "<BR>");
            	result = strToEncode;
            }
        }		
        return result;          
    }
    
    public String getTagContentByName(String tagName, String htmlText) {
		String res = "";
		Pattern ptrn = null;
		
		try {
			ptrn = Pattern.compile(".*(<\\s*" + tagName + "\\s*.*>.*?</\\s*" + tagName + "\\s*>).*",
				Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
			res = ptrn.matcher(htmlText).replaceAll("$1");
		} catch (Exception e) {
			System.err.println("getTagContentByName :: " + e.getMessage());
		}

		return res; 
	}
    
	/**
	 * Function create new trivial (original) Email
	 */
	public String getNewEmail(Boolean isNew) {
		if (isNew) {
			Date now = new Date();
			String newOriginEmail;
			newOriginEmail = "test" + u.dataTime2String(now, "ddMMyyyyHHmmss")+ "@mail.com";
			testEmail = newOriginEmail;
			return newOriginEmail;
		} else {
			return (testEmail == null ? getNewEmail(true) : testEmail);
		}
	}
	
	public String getArtist(Boolean isNew) {
		if (isNew) {
			Date now = new Date();
			String newOriginArtist;
			newOriginArtist = "Test Artist" + u.dataTime2String(now, "ddMMyyyyHHmmss");
			artistName = newOriginArtist;
			return newOriginArtist;
		} else {
			return (artistName == null ? getArtist(true) : artistName);
		}
	}
	
	public String getAlbum(Boolean isNew) {
		if (isNew) {
			Date now = new Date();
			String newOriginArtist;
			newOriginArtist = "Test Album" + u.dataTime2String(now, "ddMMyyyyHHmmss");
			albumName = newOriginArtist;
			return newOriginArtist;
		} else {
			return (albumName == null ? getAlbum(true) : albumName);
		}
	}
	
	public String getTrack(Boolean isNew) {
		if (isNew) {
			Date now = new Date();
			String newOriginArtist;
			newOriginArtist = "Test Track" + u.dataTime2String(now, "ddMMyyyyHHmmss");
			trackName = newOriginArtist;
			return newOriginArtist;
		} else {
			return (trackName == null ? getTrack(true) : trackName);
		}
	}
	
	public String getVideo(Boolean isNew) {
		if (isNew) {
			Date now = new Date();
			String newOriginArtist;
			newOriginArtist = "Test Video" + u.dataTime2String(now, "ddMMyyyyHHmmss");
			videoName = newOriginArtist;
			return newOriginArtist;
		} else {
			return (videoName == null ? getVideo(true) : videoName);
		}
	}
	
	public String getRingTone(Boolean isNew) {
		if (isNew) {
			Date now = new Date();
			String newOriginArtist;
			newOriginArtist = "Test RingTone" + u.dataTime2String(now, "ddMMyyyyHHmmss");
			ringtoneName = newOriginArtist;
			return newOriginArtist;
		} else {
			return (ringtoneName == null ? getRingTone(true) : ringtoneName);
		}
	}
	
	public String getPhysicalGood(Boolean isNew) {
		if (isNew) {
			Date now = new Date();
			String newOriginGood;
			newOriginGood = "Test PhysicalGood" + u.dataTime2String(now, "ddMMyyyyHHmmss");
			goodName = newOriginGood;
			return newOriginGood;
		} else {
			return (goodName == null ? getPhysicalGood(true) : goodName);
		}
	}
	
	public String getGroup(Boolean isNew) {
		if (isNew) {
			Date now = new Date();
			String newOriginGroup;
			newOriginGroup = "Test Group" + u.dataTime2String(now, "ddMMyyyyHHmmss");
			groupName = newOriginGroup;
			return newOriginGroup;
		} else {
			return (groupName == null ? getGroup(true) : groupName);
		}
	}
	
	public String getMessageName(Boolean isNew) {
		if (isNew) {
			Date now = new Date();
			String newOriginName;
			newOriginName = "Test Message Name" + u.dataTime2String(now, "ddMMyyyyHHmmss");
			messageName = newOriginName;
			return newOriginName;
		} else {
			return (messageName == null ? getMessageName(true) : messageName);
		}
	}
	
	public String getEmailTemplateName(Boolean isNew) {
		if (isNew) {
			Date now = new Date();
			String newOriginName;
			newOriginName = "Test Email Template Name" + u.dataTime2String(now, "ddMMyyyyHHmmss");
			messageName = newOriginName;
			return newOriginName;
		} else {
			return (messageName == null ? getMessageName(true) : messageName);
		}
	}
	
	public String getPathToRes() {			
		String absolutePath;
	    File file;
	     
		if (SeleneseTestCaseEx.getServerName().toLowerCase().contentEquals("localhost")) {
			file = new File("res");
			absolutePath = file.getAbsolutePath();
			return absolutePath;
		} else {	
			return "/home/ivanovr/res"; //Only Linux
		}

	}
	
	public void sleep(int time) {
		try {
			Thread.sleep(time);
		} catch (Exception e) {
			System.err.println("Util.sleep:" + e.getMessage());
		}
    }
	
	public void getUserFromPool(String fullPath) {
		String [] temp = null;
		Properties userPoolProp = new Properties(); 
		try {
			userPoolProp.load(new FileInputStream("userpool.properties"));
		} catch(IOException e) {
			System.err.print(e.getMessage());
		}		
		
		temp = userPoolProp.getProperty("userpool", "[NO FOUND]").split("\\;"); 

		if (temp.length == 0){
			System.out.println("Please, set 'userpool' local variable correctly in configuration file!");
		} else {
			String userPool = null;
			for (int i = 0 ; i < temp.length ; i++) {
				if(temp[i] != "") {
					if (i==0) {
						TestConfiguration tc = TestConfiguration.getInstance();
						tc.putLocalProperty(fullPath, "existuser", temp[i]);
					} else if(i==1) {
						userPool = temp[i];
						if (i!=temp.length - 1) {
							userPool = userPool + ";";
						}
					} else if(i==temp.length - 1) {
						userPool = userPool + temp[i];
					} else {
						userPool = userPool + temp[i] + ";";
					}
				}
			}
			
			userPoolProp.put("userpool", userPool);
			try {
				userPoolProp.store(new FileOutputStream("userpool.properties"), "USER POOL");
			} catch (Exception e) {
				System.out.println(e.getMessage());
			}
		}
	}
	
	public Boolean compareString(String string1, String string2, Boolean isAscSort) {
		if (string1.compareToIgnoreCase(string2) < 0 ) {
			return isAscSort? true:false; //string1 < string2 = "ascending"
		} else if(string1.compareToIgnoreCase(string2) < 0 ){
			return isAscSort? false:true; // "descending"
		} else {
			return true;
		}
	}
	
	/** Create Excel empty file
	 * @param fullPath
	 */
	public WritableWorkbook createBlankXlsFile(String fullPath) {
		WritableWorkbook wb = null;
        try {
            WorkbookSettings ws = new WorkbookSettings();
            ws.setLocale(new Locale("en", "EN"));
            wb =Workbook.createWorkbook(new File(fullPath), ws);    
       } catch (Exception e) {
            System.out.println(e.getMessage());
       }
       return wb;
	}

	
	/** Get relative path to log by alias.
	 * @param aliasFolder Alias specific log folder
	 * @return Path to specific log folder
	 * Remark:
	 * Bellow follow log hierarchy and appropriate alias
	 * log 														 = "main"
	 * log/<Release name> 										 = "release"
	 * log/<Release name>/<Test name>							 = "curtest"
	 * log/<Release name>/<Test name>/<Start time>          	 = "datetime"
	 */
	public String getPathToLog(String aliasFolder) {
		String path = "";
		
		if (aliasFolder.toLowerCase().contentEquals("main")){
			path =  "log/";
		} else if (aliasFolder.toLowerCase().contentEquals("release")) {
			path = getPathToLog("main") +  tc.getEnv("release") + "/"; 
		} else if (aliasFolder.toLowerCase().contentEquals("curtest")) {
			path = getPathToLog("release") + tc.getEnv("_testname") + "/";
		} else if (aliasFolder.toLowerCase().contentEquals("datetime")) {
			path = getPathToLog("curtest") + tc.getEnv("_testexec") + "/";
		} else if (aliasFolder.toLowerCase().contentEquals("scrsht")) {
			path = getPathToLog("datetime") + "source/scrsht/";
		} else {
			System.err.println("getPathToLog :: The '"+ aliasFolder + "' is not uknown.");
		}
		
		return path;
	}
	
	public String getFullPathToLog(String aliasFolder) {
		String path = "";
		if (!tc.getEnv("pathtologs").contentEquals("[NO FOUND]") && fw.existsFileOrDir(tc.getEnv("pathtologs"))) {
			path = tc.getEnv("pathtologs");
		} else {
			File file;
			file = new File("");
			path = file.getAbsolutePath() + "/";
		}
		path = path + getPathToLog(aliasFolder);
		path = path.replace("//", "/");
		
		return path;
	}

}
	